<template>
  <!-- 订货计划表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="850px"
    draggable
    @close="closeDialog"
    :destroy-on-close="true"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      style="display: flex"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="采购协议" prop="purchasePlanNumber">
            <el-select
              v-if="!props.isReadonly"
              @change="agreementChange"
              v-model="formData.purchasePlanNumber"
              placeholder="请选择"
              style="width: 250px"
            >
              <el-option
                v-for="item in purchasePlanNumbers"
                :key="item.id"
                :label="item.purchasePlanNumber"
                :value="item.purchasePlanNumber"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 订单编号-->
        <el-col :span="12" v-if="formData.id">
          <el-form-item label="计划编号" :span="12">
            <el-input
              v-model="formData.orderNo"
              style="width: 250px"
              disabled
            />
          </el-form-item>
        </el-col>
        <!-- 工厂号-->
        <el-col :span="12">
          <el-form-item label="工厂" :span="12">
            <el-select
              v-if="!props.isReadonly"
              @change="plantChange"
              v-model="formData.plantId"
              placeholder="请选择"
              style="width: 250px"
              disabled
            >
              <el-option
                v-for="item in plants"
                :key="item.plantId"
                :label="item.plantName"
                :value="item.plantId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.partnerId"
              placeholder="请选择"
              style="width: 250px"
              disabled
            >
              <el-option
                v-for="item in partners"
                :key="item.partnerId"
                :label="item.partnerName"
                :value="item.partnerId"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!--物料号-->
        <el-col :span="12">
          <el-form-item label="物料">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.materialId"
              placeholder="请选择"
              style="width: 250px"
              disabled
            >
              <el-option
                v-for="item in materials"
                :key="item.materialId"
                :label="item.materialName"
                :value="item.materialId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!--计划到货日期-->
        <el-col :span="12">
          <el-form-item label="计划到货日期" prop="arriveDate">
            <el-date-picker
              v-model="formData.arriveDate"
              type="date"
              placeholder="请输入到货日期"
              style="width: 250px"
              :disabled-date="disabledDate"
            />
          </el-form-item>
        </el-col>
        <!--      要货地点-->
        <el-col :span="12">
          <el-form-item label="要货地点" prop="storageLocationName">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.storageLocationId"
              placeholder="请选择要货地点"
              style="width: 250px"
              @change="storageLocationChange"
            >
              <el-option
                v-for="item in storageLocations"
                :key="item.id"
                :label="item.storageLocationName"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.storageLocationName }}</span>
          </el-form-item>
        </el-col>
        <!--      计划采购周期类型-->
        <el-col :span="12">
          <el-form-item label="计划周期类型" prop="purchasingCycleType">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.purchasingCycleType"
              placeholder="请输入采购周期类型"
              style="width: 250px"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList(
                  'PurchasingCycleType'
                )"
                :key="item.value"
                :label="item.label"
                :value="Number(item.value)"
              />
            </el-select>
            <span v-else>{{ formData.purchasingCycleType }}</span>
          </el-form-item>
        </el-col>
        <!--      计划采购数量-->
        <el-col :span="12">
          <el-form-item label="计划采购数量" prop="planQuantity">
            <el-input-number
              v-model="formData.planQuantity"
              :min="minBatchQuantity"
              :max="maxPlanQuantity"
              style="width: 250px"
            />
          </el-form-item>
        </el-col>
        <!--备注-->
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.remarks"
            placeholder="请输入备注"
            type="textarea"
            :rows="2"
            style="width: 655px"
          />
          <span v-else>{{ formData.remarks }}</span>
        </el-form-item>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SRMSRMORDERSCHEDULEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
// 工厂
let plants: any = ref([]);
// 物料号
let materials: any = ref([]);
// 供应商
let partners: any = ref([]);
// 采购协议
let purchasePlanNumbers = ref([]);
// 要货地点
let storageLocations = ref([]);

// 最大最小采购量
let minBatchQuantity = ref(0);
let maxPlanQuantity = ref(0);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    getPurchasePlanNumbersInfo(formData.purchasePlanNumber);
  }
);
// 表单校验规则
const rules = reactive({
  plantId: [{ required: true, message: "未选择工厂", trigger: "change" }],
  partnerId: [{ required: true, message: "未选择供应商", trigger: "change" }],
  arriveDate: [
    {
      required: true,
      type: "date",
      message: "未选择到货日期",
      trigger: "change",
    },
  ],
  materialId: [{ required: true, message: "未选择物料", trigger: "change" }],
  storageLocationName: [
    { required: true, message: "未选择要货地点", trigger: "change" },
  ],
  planQuantity: [],
  purchasingCycleType: [
    { required: true, message: "未选择周期类型", trigger: "change" },
  ],
  purchasePlanNumber: [
    { required: true, message: "未选择采购协议", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  beginDate: [],
  endDate: [],
  filename: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  orderNo: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  purchasePlanNumber: "",
  partnerId: "",
  partnerCode: "",
  materialId: "",
  materialNumber: "",
  materialName: "",
  storageLocationId: "",
  storageLocationCode: "",
  storageLocationName: "",
  arriveDate: "",
  arriveYear: "",
  arriveMonth: "",
  arriveWeek: "",
  purchasingCycleType: "",
  planQuantity: 0,
  agreeQuantity: "",
  unitCode: "",
  replyUserId: "",
  replyUserName: "",
  replyTime: "",
  replyContent: "",
  orderScheduleState: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  deleted: "",
  beginDate: "",
  endDate: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        orderNo,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        purchasePlanNumber,
        partnerId,
        partnerCode,
        materialId,
        materialNumber,
        materialName,
        storageLocationId,
        storageLocationCode,
        storageLocationName,
        arriveDate,
        arriveYear,
        arriveMonth,
        arriveWeek,
        purchasingCycleType,
        planQuantity,
        agreeQuantity,
        unitCode,
        replyUserId,
        replyUserName,
        replyTime,
        replyContent,
        orderScheduleState,
        remarks,
        createTime,
        createdUserId,
        lastUpdateTime,
        lastUpdatedUserId,
        deleted,
        beginDate,
        endDate,
      } = newVal;
      Object.assign(formData, {
        id,
        orderNo,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        purchasePlanNumber,
        partnerId,
        partnerCode,
        materialId,
        materialNumber,
        materialName,
        storageLocationId,
        storageLocationCode,
        storageLocationName,
        arriveDate,
        arriveYear,
        arriveMonth,
        arriveWeek,
        purchasingCycleType,
        planQuantity,
        agreeQuantity,
        unitCode,
        replyUserId,
        replyUserName,
        replyTime,
        replyContent,
        orderScheduleState,
        remarks,
        createTime,
        createdUserId,
        lastUpdateTime,
        lastUpdatedUserId,
        deleted,
        beginDate,
        endDate,
      });
    }
  }
);
onMounted(() => {
  // 根据登入人所在工厂id查询采购协议 按照一个权限工厂算
  getPurchasePlanNumbers();
});
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.orderNo = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.purchasePlanNumber = "";
  formData.partnerId = "";
  formData.partnerCode = "";
  formData.materialId = "";
  formData.materialNumber = "";
  formData.materialName = "";
  formData.storageLocationId = "";
  formData.storageLocationCode = "";
  formData.storageLocationName = "";
  formData.arriveDate = "";
  formData.arriveYear = "";
  formData.arriveMonth = "";
  formData.arriveWeek = "";
  formData.purchasingCycleType = "";
  formData.planQuantity = 0;
  formData.agreeQuantity = "";
  formData.unitCode = "";
  formData.replyUserId = "";
  formData.replyUserName = "";
  formData.replyTime = "";
  formData.replyContent = "";
  formData.orderScheduleState = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.deleted = "";
  formData.beginDate = "";
  formData.endDate = "";
}

const loading = ref(false);
// 禁用当前日期之前日期(不包含当天日期)
const disabledDate = (time: Date) => {
  return time.getTime() <= Date.now() - 8.64e7;
};
//获取所有采购协议
async function getPurchasePlanNumbers() {
  request({
    url: `/srm/core/srmorderschedule/agreement`,
    method: "get",
  }).then((data) => {
    purchasePlanNumbers.value = data.data;
  });
}

//根据采购协议号获取采购协议
async function getPurchasePlanNumbersInfo(number: string) {
  // 清楚编辑带来的数据留存问题
  plants.value = [];
  materials.value = [];
  partners.value = [];
  storageLocations.value = [];
  //接受index所传对象并且获取所编辑的工厂id
  let planAgreement = JSON.parse(JSON.stringify(props.data));
  await getStorageLocation(formData.plantId);
  //选择协议时查寻改协议，并在查询前清除原有数据
  if (number != "") {
    plants.value = [];
    materials.value = [];
    partners.value = [];
    storageLocations.value = [];
    request({
      url: `/srm/core/srmorderschedule/plan/${number}`,
      method: "get",
      // data: { purchasePlanNumber: number },
    })
      .then((data) => {
        plants.value.push({
          plantId: data.data.plantId,
          plantName: data.data.plantName,
        });
        formData.plantId = plants.value[0].plantId;
        plantChange();
        materials.value.push({
          materialId: data.data.materialId,
          materialName: data.data.materialName,
        });
        formData.materialId = materials.value[0].materialId;
        partners.value.push({
          partnerId: data.data.partnerId,
          //此处用的是供应商名称，不是编号
          partnerName: data.data.partnerName,
        });
        formData.partnerId = partners.value[0].partnerId;
        formData.planQuantity = data.data.minBatchQuantity;
        minBatchQuantity.value = data.data.minBatchQuantity;
        maxPlanQuantity.value = data.data.maxPlanQuantity;
        formData.plantCode = data.data.plantCode;
        formData.plantName = data.data.plantName;
        formData.partnerCode = data.data.partnerCode;
        // formData.partnerName = data.data.partnerName;
        formData.materialNumber = data.data.materialNumber;
        formData.materialName = data.data.materialName;
        formData.purchasePlanNumber = data.data.purchasePlanNumber;
        formData.beginDate = data.data.beginDate;
        formData.endDate = data.data.endDate;
        formData.organizationId = data.data.organizationId;
        formData.organizationCode = data.data.organizationCode;
        formData.organizationName = data.data.organizationName;
      })
      .catch((res) => {
        // console.log(res);
      });
  }
}

// 根据工厂ID查询该工厂要货地点
async function getStorageLocation(id: string) {
  request({
    url: `/srm/core/storagelocation/getList`,
    method: "post",
    data: { plantId: id },
  }).then((data) => {
    storageLocations.value = data.data;
  });
}
// 协议改变
function agreementChange() {
  getPurchasePlanNumbersInfo(formData.purchasePlanNumber);
  for (let key in formData) {
    if (
      key != "purchaseNumber" &&
      key != "planQuantity" &&
      key != "purchasingCycleType" &&
      key != "arriveDate" &&
      key != "remarks" &&
      key != "id"
    ) {
      formData[key] = "";
    }
    if (key == "planQuantity") {
      formData[key] = 0;
      minBatchQuantity.value = 0;
      maxPlanQuantity.value = 0;
    }
  }
  plants.value = [];
  materials.value = [];
  partners.value = [];
  storageLocations.value = [];
}

// 工厂变动查询工厂收货地点
function plantChange() {
  if (formData.plantId != "") {
    getStorageLocation(formData.plantId);
  }
  storageLocations.value = [];
}

function storageLocationChange() {
  const storageLocation = storageLocations.value.find((item) => {
    return item.id === formData.storageLocationId;
  });
  formData.storageLocationCode = storageLocation.storageLocationCode;
  formData.storageLocationName = storageLocation.storageLocationName;
}

/** 订货计划保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/srm/core/srmorderschedule/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
